﻿using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;

namespace Helper
{
    /// <summary>
    /// 코드 페이지
    /// </summary>
    public enum CodePage
    {
        UTF8 = 65001,
        EUCKR = 949
    }

    /// <summary>
    /// 유틸리티 도우미 클래스
    /// </summary>
    public class UtilHelper
    {

        #region public string GetPageSource()

        /// <summary>
        /// 인터넷 HTML 소스를 가져옵니다.
        /// </summary>
        /// <param name="url">가져올 페이지 URL</param>
        /// <returns></returns>
        public string GetPageSource(string url)
        {
            return GetPageSource(url, CodePage.UTF8);
        }

        /// <summary>
        /// 인터넷 HTML 소스를 가져옵니다.
        /// </summary>
        /// <param name="url">가져올 페이지 URL</param>
        /// <param name="EncodingType">인코딩 타입</param>
        /// <returns></returns>
        public string GetPageSource(string url, CodePage EncodingType)
        {
            HttpWebRequest hwReq = (HttpWebRequest)WebRequest.Create(url);
            WebResponse wRes = hwReq.GetResponse();
            StreamReader sr = new StreamReader(wRes.GetResponseStream(), System.Text.Encoding.GetEncoding((int)EncodingType));
            string rst = sr.ReadToEnd();
            sr.Close();
            wRes.Close();

            return rst;
        }

        #endregion

        /// <summary>
        /// 지정한 경로에 폴더를 생성합니다.
        /// </summary>
        /// <param name="virtualPath">가상 경로</param>
        public void MakeFolder(string virtualPath)
        {
            HttpServerUtility Server = HttpContext.Current.Server;
            Regex rx = new Regex(@"/$");
            virtualPath = rx.Replace(virtualPath, "");

            string localPath = Server.MapPath(virtualPath);

            if (!Directory.Exists(localPath))
            {
                int idx = virtualPath.LastIndexOf("/");
                if (idx > -1)
                    MakeFolder(virtualPath.Substring(0, idx));
                if (!Directory.Exists(localPath))
                    Directory.CreateDirectory(localPath);
            }

        }
    }
}